package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DestinationServiceImpl implements IDestinationService {
    @Autowired
    private DestinationRepository destinationRepository;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private MongoTemplate template;
    @Override
    public void save(Destination destination) {
        destination.setId(null);
        destinationRepository.save(destination);
    }

    @Override
    public void update(Destination destination) {
        destinationRepository.save(destination);
    }

    @Override
    public void delete(String id) {
        destinationRepository.deleteById(id);
    }

    @Override
    public Destination get(String id) {
        return destinationRepository.findById(id).orElse(null);
    }

    @Override
    public List<Destination> listAll() {
        return destinationRepository.findAll();
    }


    @Override
    public List<Destination> queryDestByRegionId(String rid) {
        //根据id查询当前的区域下的目的地数据的id
        Region region = regionService.get(rid);
        // 拿到区域id查询对应的目的地数据
        return destinationRepository.findByIdIn(region.getRefIds());
    }

    @Override
    public Page<Destination> query(DestinationQuery qo) {
        Query query = new Query();
        // 添加查询条件
        if (!StringUtils.hasLength(qo.getParentId())) {
            query.addCriteria(Criteria.where("parentId").is(null));
        }else {
            query.addCriteria(Criteria.where("parentId").is(qo.getParentId()));
        }
        if (StringUtils.hasLength(qo.getKeyword())) {
            query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }
        // 添加分页参数查询分页的内容
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
       return DBHelper.query(template,pageable,query,Destination.class);
    }

    @Override
    public List<Destination> findByParentId(String parentId) {
        // 中国 >> 广东 >> 广州
        List<Destination> list = new ArrayList<>();
        if (StringUtils.hasLength(parentId)) {
            // 查询出当前的区域(直到没有parentId时即可)
            while (parentId != null){
                //带有parentId的表示有上级
                // 查出该parentId的目的地数据，并且放到集合中
                Destination destination = this.get(parentId);
                list.add(destination);
                // 再使用查出来的目的地数据查出parentId的值（有：继续查询放到集合； 没有：跳出循环）
                parentId = destination.getParentId();
            }
            // 把数据反转
            Collections.reverse(list);
        }
        return list;
    }

    @Override
    public void updateInfo(Destination destination) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(destination.getId()));
        Update update = new Update();
        update.set("info", destination.getInfo());
        template.updateMulti(query, update, Destination.class);
    }

    @Override
    public List<Destination> queryDestByRegionIdForApi(String regionId) {
        List<Destination> list = new ArrayList();
        if ("-1".equals(regionId)) {
            // regionId为-1时只查询中国的数据
            list = destinationRepository.findByParentName("中国");
        }else {
            // 根据区域id插叙对应的目的地
            list = this.queryDestByRegionId(regionId);
        }
        for (Destination destination : list) {
            // 拿到父级的id，作为子类的parentId为查询条件
            String subParentId = destination.getId();
            // 根据当前目的地id查询下一级的目的地数据
            // 添加数据的限制条件
            Pageable pageable = PageRequest.of(0,5, Sort.Direction.ASC,"_id");
            List<Destination> subTitle = destinationRepository.findByParentId(subParentId,pageable);
            destination.setChildren(subTitle);
        }
        return list;
    }

    @Override
    public List<Destination> queryDestByDeep(int deep) {
        return destinationRepository.findByDeep(deep);
    }

    @Override
    public Destination findByName(String keyword) {
        return destinationRepository.findByName(keyword);
    }
}
